import CryptoJS from 'crypto-js';

const CryptoSecret = '__CryptoJS_Secret__'

/**
 * 加密数据
 * @param data - 数据
 * @param secret - 密钥
 */
export function encrypto(data: any, secret?: string) {
  const newData = JSON.stringify(data)
  return CryptoJS.AES.encrypt(newData, secret || CryptoSecret).toString()
}

export function encryptByDES(message: any, secret?: string) {
  const keyHex = CryptoJS.enc.Utf8.parse(secret || CryptoSecret)
  const encrypted = CryptoJS.DES.encrypt(message, keyHex, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7
  })
  return encrypted.toString()
}

/**
 * 解密数据
 * @param cipherText - 密文
 * @param secret - 密钥
 */
export function decrypto(cipherText: string, secret?: string) {
  const bytes = CryptoJS.AES.decrypt(cipherText, secret || CryptoSecret)
  const originalText = bytes.toString(CryptoJS.enc.Utf8)
  if (originalText) {
    return JSON.parse(originalText)
  }
  return null
}
